package com.longrise.android.byjk.plugins.aboutme;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.permission.PermissionUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.utils.PhoneUtils;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.byjk.widget.view.InputBoxView;

public class SuggestionLFView extends BaseActivity implements OnClickListener, TextWatcher {

    private static final String TAG = "SuggestionLFView";

    private Toolbar mTitle;

    private Button mText_Commit;
    private Button mText_CallSer;
    private EditText mEdit_Sug;

    private InputBoxView mEtphone;

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_suggesttion;
    }

    @Override
    public void initView() {
        mText_Commit = (Button) findViewById(R.id.text_com);
        mEdit_Sug = (EditText) findViewById(R.id.edit_sug);
        mText_CallSer = (Button) findViewById(R.id.text_call_server);
        mEtphone = (InputBoxView) findViewById(R.id.edit_phonenum);
        mText_Commit.setEnabled(false);
        regEvent();

        String userphone = UserInfor.getInstance().getUserphone();
        if (!TextUtils.isEmpty(userphone)) {
            mEtphone.setText(userphone);
            mEtphone.getEditText().setSelection(userphone.length());
        }

        initTitle();

        Tracker_Google.getInstance().addGoogleScreenName("咨询建议");
    }

    private void initTitle() {
        mTitle = (Toolbar) findViewById(R.id.byjk_toolbar);
        mTitle.setTitle(getString(R.string.comment_title));
        mTitle.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
                hideInputMegthod();
            }
        });
    }

    private void regEvent() {
        if (mText_Commit != null) {
            mText_Commit.setOnClickListener(this);
        }
        if (mText_CallSer != null) {
            mText_CallSer.setOnClickListener(this);
        }

        mEtphone.getEditText().addTextChangedListener(this);
        mEdit_Sug.addTextChangedListener(this);
    }

    private void packageData() {
        String sug = mEdit_Sug.getText().toString().trim();
        if (sug.equals("")) {
            DZZWTools.showToast(this, getString(R.string.please_input_comment), Toast.LENGTH_SHORT);
            return;
        }
        //手机号码
        String phonenum = mEtphone.getText().toString().trim();
        if (TextUtils.isEmpty(phonenum)) {
            DZZWTools.showToast(this, getString(R.string.please_input_phone), Toast.LENGTH_SHORT);
            return;
        }
        if (!PhoneUtils.isPhoneNumber(phonenum)) {
            DZZWTools.showToast(this, getString(R.string.phone_type_error), Toast.LENGTH_SHORT);
            return;
        }
        String isRealCardNo = UserInfor.getInstance().getIsRealCardNo();
        String cardno = isRealCardNo.equals("1") ? UserInfor.getInstance().getUsersfzh() : UserInfor.getInstance().getUserName();
        if (!NetUtil.checkNetEnable()) {
            return;
        }
        switchButtonState(false);
        clientRequest(sug, phonenum, cardno);
    }

    private void switchButtonState(boolean b) {
        mText_Commit.setEnabled(b);
        mText_Commit.setClickable(b);
    }

    private void clientRequest(String content, String phonenum, String cardno) {
        DZZWTools.showWaitDialog(this);
        EntityBean bean = new EntityBean();
        bean.set("fdemail", phonenum);
        bean.set("content", content);
        bean.set("cardno", cardno);
        EntityBean serBean = new EntityBean();
        serBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_user_iFeedback", serBean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    clientParse(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished(String key, String service) {
                switchButtonState(true);
                DZZWTools.dismissDialog(null);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                DZZWTools.showToast(SuggestionLFView.this, getResources().getString(R.string.networkerror), 1000 * 2);
            }
        });
    }

    private void clientParse(Object result) throws Exception {
        EntityBean bean = (EntityBean) result;
        int state = bean.getInt("resultstate");
        if (state == 1) {
            DZZWTools.showToast(this, getString(R.string.comment_commit_success), Toast.LENGTH_SHORT);
            mEdit_Sug.setText("");
        } else {
            DZZWTools.showToast(this, bean.getString("resultdesc"), Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_com:
                packageData();
                break;

            case R.id.text_call_server:
                checkPhonePermission();
                break;

            default:
                break;
        }
    }

    private void checkPhonePermission() {
        PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.PHONE, "电话权限", "电话权限必须的\n否者我们无法为您提供\n拨打电话功能", new PermissionUtil.PermissionCallBack() {
            @Override
            public void onSuccess() {
                call(getString(R.string.callserver));
            }

            @Override
            public void onDenied() {
            }
        });
    }

    private void call(String phonenumber) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri uri = Uri.parse("tel:" + phonenumber);
        intent.setData(uri);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        startActivity(intent);
    }

    private void hideInputMegthod() {
        try {
            InputMethodManager manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            if (manager.isActive()) {
                manager.hideSoftInputFromWindow(mEdit_Sug.getWindowToken(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是否全部填写
     *
     * @return 全部有填写 返回true
     */
    private boolean checkText() {
        //手机号
        String phoneNum = mEtphone.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNum)) {
            return false;
        }
        //咨询建议
        String mIbvVfcodeText = mEdit_Sug.getText().toString().trim();
        if (TextUtils.isEmpty(mIbvVfcodeText)) {
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        boolean b = checkText();
        if (b) {
            mText_Commit.setEnabled(true);
        } else {
            mText_Commit.setEnabled(false);
        }
    }
}
